<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NAvatar,
  NButton,
  NCheckbox,
  NCheckboxGroup,
  NForm,
  NFormItem,
  NImage,
  NInput,
  NSpace,
  NSwitch,
  NTag,
  NPopconfirm,
  NLayout,
  NLayoutSider,
  NLayoutContent,
  NTreeSelect, NSelect, NFlex, useMessage, NDataTable
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import QueryBarItem from '@/components/query-bar/QueryBarItem.vue'
import CrudModal from '@/components/table/CrudModal.vue'
import CrudTable from '@/components/table/CrudTable.vue'
import {formatDate, formatDateTime, getToken, renderIcon} from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import TheIcon from '@/components/icon/TheIcon.vue'
import { useUserStore } from '@/store'
const base_path = import.meta.env.VITE_BASE
import default_image from "@/assets/images/mz.jpg"
import { exportToExcel } from '@/utils/exportUtils'

defineOptions({ name: '进销存总表' })
const instance = getCurrentInstance();
const nameFromInstance = instance?.type.name;

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const message = useMessage()

const data = reactive({
  uploadAction: base_path+'/system/base/userimg',
  token: getToken(),
  data_ini:{
    type: [],
    category_id:[]
  },
   config:[],
   durgs:[],
    DrugsDepository:[],
    DrugsNumber:[],
    select_durg_id:null
})

const {
  modalVisible,
  modalTitle,
  modalAction,
  modalLoading,
  handleSave,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
} = useCRUD({
  name: '进销存总表',
  initForm: {},
  doCreate: api.createDrugsBills,
  doUpdate: api.updateDrugsBills,
  doDelete: api.deleteDrugsBills,
  refresh: () => $table.value?.handlerefresh(),
})


onMounted(() => {
    $table.value?.handleSearch()
    api.getConfig().then((res) => {
      data.config = res.data
    })
})

const handleExport = async () => {
  try {
    // 显示加载状态
    const loading = message.loading('正在准备导出数据...', { duration: 0 })

    // 获取表格数据
    const { data: tableData } = await api.getDrugsDepositoryList({
      ...queryItems.value,
      is_export:1
    })

    if (!tableData || tableData.length === 0) {
      message.warning('没有数据可以导出')
      return
    }

    // 处理数据格式
    const exportData = tableData.map(item => ({
      库房: item.depository_name,
      药品编号: item.drugs_id,
      药品名称: item.drugs?.name || '',
      分类: item.category_name,
      规格: item.drugs?.spec || '',
      单位: item.drugs?.unit || '',
      现有库存: item.total_number,
      现有成本: item.total_price,
      期初数量: item.qc_nums,
      期初成本: item.qc_price,
      期初单价: item.qc_single_price,
      期中入库: item.qzrk_nums,
      入库成本: item.qzrk_price,
      期中入库单价: item.qzrk_single_price,
      期中出库: item.qzck_nums,
      出库成本: item.qzck_price,
      期中出库单价: item.qzck_single_price,
      期末数量: item.qm_nums,
      期末成本: item.qm_price,
      期末单价: item.qm_single_price
    }))

    // 导出Excel
    exportToExcel(exportData, `进销存总表_${formatDate(new Date())}`)
    message.success('导出成功')
    loading?.destroy()
  } catch (error) {
    console.error('导出失败:', error)
    message.error('导出失败: ' + error.message)
  } finally {
    loading?.destroy()
  }
}

const columns = [

    {
    title: '库房',
    key: 'depository_name',
    width: 60,
    align: 'center',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.depository_name	 })
    },
  },
    {
    title: '药品编号',
    key: 'drugs_id',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '药品名称',
    key: 'drugs.name',
    width: '140',
    align: 'center',
      fixed: 'left',
    render(row) {
      return h(NTag, { type: 'primary',size:"small",bordered:false, style: { margin: '2px 3px' } }, { default: () => row.drugs.name	 })
    },
  },
    {
    title: '分类',
    key: 'category_name',
    width: 50,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '规格',
    key: 'drugs.spec',
    width: 50,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '单位',
    key: 'drugs.unit',
    width: 30,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '现有库存',
    key: 'total_number',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '现有成本',
    key: 'total_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期初数量',
    key: 'qc_nums',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期初成本',
    key: 'qc_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期初单价',
    key: 'qc_single_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期中入库',
    key: 'qzrk_nums',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },

    {
    title: '入库成本',
    key: 'qzrk_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
  {
    title: '期中入库单价',
    key: 'qzrk_single_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期中出库',
    key: 'qzck_nums',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '出库成本',
    key: 'qzck_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
     {
    title: '期中出库单价',
    key: 'qzck_single_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期末数量',
    key: 'qm_nums',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期末成本',
    key: 'qm_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  },
    {
    title: '期末单价',
    key: 'qm_single_price',
    width: 40,
    align: 'center',
    ellipsis: { tooltip: true },
  }

]

function formatTimestamp(timestamp) {
  const date = new Date(timestamp)
  const pad = (num) => num.toString().padStart(2, '0')
  const year = date.getFullYear()
  const month = pad(date.getMonth() + 1) // 月份从0开始，所以需要+1
  const day = pad(date.getDate())
  const hours = pad(date.getHours())
  const minutes = pad(date.getMinutes())
  const seconds = pad(date.getSeconds())
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
const datetimeRange = ref()
const handleDateRangeChange = (value) => {
  queryItems.value.start_time = formatTimestamp(value[0])
  queryItems.value.end_time = formatTimestamp(value[1])
}

</script>

<template>
  <NLayout has-sider wh-full>
    <NLayoutContent style="background: transparent;margin-left: 20px;">
      <CommonPage show-footer title="进销存总表">
        <template #action>
          <NSpace>
            <NButton type="primary" @click="handleExport">
              <TheIcon icon="material-symbols:download" :size="18" class="mr-5" />导出Excel
            </NButton>
          </NSpace>
        </template>
        <!-- 表格 -->
        <CrudTable
          ref="$table"
          v-model:query-items="queryItems"
          :columns="columns"
          :get-data="api.getDrugsDepositoryList"
           :scroll-x="2000"
        >
          <template #queryBar>
            <QueryBarItem label="仓库名称" :label-width="80">
               <NSelect
                  v-model:value="queryItems.depository_id"
                  :options="data.config.depository"
                  placeholder="请选择仓库"
                  filterable
                  label-field="name"
                  value-field="id"
                />
            </QueryBarItem>
            <QueryBarItem label="药品名称" :label-width="80">
              <NInput
                v-model:value="queryItems.title"
                clearable
                type="text"
                placeholder="药品名称"
                style="width: 200px;"
              />
            </QueryBarItem>
            <QueryBarItem label="统计时间" :label-width="70">
              <NDatePicker
                  v-model:value="datetimeRange"
                  type="datetimerange"
                  clearable
                  placeholder="请选择时间范围"
                  @update:value="handleDateRangeChange"
              />
            </QueryBarItem>

          </template>
        </CrudTable>


      </CommonPage>
    </NLayoutContent>
  </NLayout>
  <!-- 业务页面 -->
</template>
